#include "logcatserver.h"
#include <QTcpSocket>
#include <QDebug>
#include <QXmlStreamWriter>
#include <QDomDocument>
#include <QTimer>

//QTimer m_timer;
LogCatServer*  LogCatServer::m_instance = NULL;
LogCatServer* LogCatServer::getInstance(QObject *parent)
{
    if(m_instance == NULL)
    {
        m_instance = new LogCatServer(parent);
    }
    return m_instance;
}

void LogCatServer::sendLog(QByteArray log)
{
    int len = log.length();
    char lenchar[4]={0};
    memcpy(lenchar, &len, 4);
    for(int i= 0;i< m_clientList.size(); i++)
    {
        m_clientList.at(i)->write(&lenchar[0], 1);
        m_clientList.at(i)->write(&lenchar[1], 1);
        m_clientList.at(i)->write(&lenchar[2], 1);
        m_clientList.at(i)->write(&lenchar[3], 1);
        m_clientList.at(i)->write(log);
    }
}
QString LogCatServer::typeToName(QtMsgType type)
{
    QString typestr;
    switch (type) {
    case QtDebugMsg:
        typestr = "d";
        break;
    case QtWarningMsg:
        typestr = "w";
        break;
    case QtCriticalMsg:
        typestr = "c";
        break;
    case QtFatalMsg:
        typestr = "e";
        break;
    default:
        break;
    }

    return typestr;
}

void LogCatServer::sendLog(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    xmlStream.writeStartElement("log");
    xmlStream.writeAttribute("type",typeToName(type));
    xmlStream.writeTextElement( "version", QString::number(context.version));
    xmlStream.writeTextElement( "line", QString::number(context.line));
    xmlStream.writeTextElement( "file", context.file);
    xmlStream.writeTextElement( "function", context.function);
    xmlStream.writeTextElement( "category", context.category);
    xmlStream.writeTextElement( "msg", msg.toHtmlEscaped());
    xmlStream.writeEndElement();
    sendLog(data);
}

void LogCatServer::manageClient()
{
    QTcpSocket  *socket = nextPendingConnection();
    m_clientList << socket;

    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    xmlStream.writeStartElement("log");
    xmlStream.writeAttribute("type","");
    xmlStream.writeTextElement( "version", "");
    xmlStream.writeTextElement( "line", "");
    xmlStream.writeTextElement( "file", "LogCatServer");
    xmlStream.writeTextElement( "function", "welcome");
    xmlStream.writeTextElement( "category", "");
    xmlStream.writeTextElement( "msg", "welcome to use logcat");
    xmlStream.writeEndElement();
    sendLog(data);

}

LogCatServer::LogCatServer(QObject *parent) :
    QTcpServer(parent)
{
    connect(this, SIGNAL(newConnection()),this, SLOT(manageClient()));
    listen(QHostAddress::Any, 10000);
}
